package com.xiaohudie.Pojo;

import com.sun.istack.internal.logging.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalTime;
import java.util.Arrays;

@Aspect
@Component
/**AOP控制类*/
public class AopClass {
    private Logger logger = Logger.getLogger(getClass());
    /**定义切入点
     * 在controller包下的所有接口*/
    @Pointcut("@annotation(com.xiaohudie.Pojo.Aop)")
    public void PointCut(){

}
   @Before("@annotation(com.xiaohudie.Pojo.Aop)")
    public void Before(JoinPoint joinPoint){
       Signature signature = joinPoint.getSignature();
       LocalTime now = LocalTime.now();
       String name = signature.getName();
       ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
       HttpServletRequest request = requestAttributes.getRequest();
       //记录请求内容
       logger.info("URL : "+request.getRequestURL().toString());logger.info("HTTP_METHOD : " + request.getMethod());
       logger.info("IP : " + request.getRemoteAddr());
       logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
       logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
       System.out.println("进入"+name+"的时间为:"+now);
       System.out.println("在"+name +"请求来之前");
   }
   @Around("@annotation(com.xiaohudie.Pojo.Aop)")
    public Object Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
       System.out.println("环绕操作之后");
       MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
       Method method = signature.getMethod();
       /**拿到这个方法的参数*/
       Object[] args = proceedingJoinPoint.getArgs();
       args[1] ="无效的哈哈哈";
       args[0] =new Integer((Integer)(args[0])*10);
       xiaohudie annotation = method.getAnnotation(xiaohudie.class);
       String type;
       if (annotation.type()!=null) {
           type = annotation.type();
       }else {
           type ="空空空";
       }
       System.out.println("type为"+type);
      return  proceedingJoinPoint.proceed(args);
    }
    @After("@annotation(com.xiaohudie.Pojo.Aop)")
    public void After(){
        System.out.println("在请求之后");
    }
    @AfterReturning("@annotation(com.xiaohudie.Pojo.Aop)")
    public void AfterReturning(){
        System.out.println("在返回值之后");
    }
}
